package cn.itcast.bassm.service.impl;


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import cn.itcast.bassm.mapper.PushMapper;
import cn.itcast.bassm.mapper.UserMapper;
import cn.itcast.bassm.pojo.Push;
import cn.itcast.bassm.pojo.Returnxx;
import cn.itcast.bassm.pojo.Shooting;
import cn.itcast.bassm.pojo.Unitdoor;
import cn.itcast.bassm.pojo.UserInformation;
import cn.itcast.bassm.pojo.Visitors;
import cn.itcast.bassm.service.PushService;
import cn.itcast.bassm.util.Page;
import cn.itcast.bassm.util.readTxT;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
@Service
public class PushServiceImpl implements PushService {
	
	private static Logger mLogger = Logger.getLogger("PushServiceImpl");
	String Localfaceuser="admin";
	String passwork="123456";
	private final String CONTENT_TYPE_TEXT_JSON = "text/json";
	
	@Autowired
	public PushMapper pushMapper;
	@Autowired
	private UserMapper userMapper;
	
	public void savePush(String scenePath) {
		try {
			//Timestamp Timestamptime =Transformationlong(datelong);
			//PushServiceImpl saveimg = new PushServiceImpl();
			//String scenePath1=saveJPG(scenePath);
			//pushMapper.savePush(scenePath1, Timestamptime);
			String pathtuisong=scenePath;
			userMapper.insertpathtuisong(pathtuisong);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/*
	 * 
	 * long转换成timestamp
	 */
	public Timestamp Transformationlong(long datelong) throws ParseException{
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1= new Date(datelong);
        String data1=sdf.format(date1);
        Timestamp d2 = Timestamp.valueOf(data1);
        return d2;
    }
	
	/**
	 * 通过URL保存图片
	 * 
	 */
	public  String saveJPG(String urlString) throws Exception{
		Date data=new Date();
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String updatetime = dateFormat.format(data);
		String datelong1=updatetime; 
		String filename="C:\\testimg\\"+datelong1+".jpg";
		// 构造URL
	    URL url = new URL(urlString);
	    // 打开连接
	    URLConnection con = url.openConnection();
	    // 输入流
	    InputStream is = con.getInputStream();
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流
	    OutputStream os = new FileOutputStream(filename);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    String scenePath=filename;
	    // 完毕，关闭所有链接
	    os.close();
	    is.close();
	    return scenePath;
	}
	/**
	 * 用户信息展示列表
	 */
	public List<UserInformation> finPushUser() {
		List<UserInformation>list=pushMapper.finPushUser();
		return list;
	}
	
	/**
	 * 查询推送img信息
	 */
	public List<Push> showFinUserImg(){
		List<Push>push=pushMapper.showFinUserImg();
		return push;
	}
	
	/**
	 * 访客列表查询
	 */
	public void showBvisitorProductsByPage(String pageNow, String name,
			Model model) {
		 Page page = null;  
		    List<Visitors> products = new ArrayList<Visitors>();   
		    List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
		    List<Shooting> shooting = new ArrayList<Shooting>();
		    String Celladdress1=name;
		    int totalCount = (int) pushMapper.getProductsCount(Celladdress1);
		  
		    if (pageNow != null) {  
		        page = new Page(totalCount, Integer.parseInt(pageNow));  
		        products = this.pushMapper.selectProductsByPage(page.getStartPos(),Celladdress1, page.getPageSize());

		    } else {  
		        page = new Page(totalCount, 1);  
		        products = this.pushMapper.selectProductsByPage(page.getStartPos(),Celladdress1, page.getPageSize()); 
		   
		    }
		    String address=name;
		    shooting = pushMapper.selcetShooting(address);
		    model.addAttribute("shooting",shooting);
		    model.addAttribute("products", products);
		    model.addAttribute("address", address);
		    model.addAttribute("page", page);
		
	}
	public Returnxx addqueryUserById(String id, String num,String nameone) throws Throwable {
		String yid= id;
		Visitors u =pushMapper.addqueryUserById(yid);
		int id2 = u.getYid();
		String urlimglist=u.getYimageurl();
		String facepath=urlimglist;
		String sfzid =u.getYphone();
		String sex = u.getYsex();
		String detailed = u.getYaddress();
		String name =u.getYname();
		String phong = u.getYphone();
		String phone=phong;
		String state =u.getYindate();
		boolean msg = addWhitePersion(facepath, name, phone, detailed, sex,sfzid,state,id2,num,nameone);
		Returnxx r = new Returnxx();
		if(!msg){
			String usermsg="0";
			r.setMsg(usermsg);
			return r;
		}else {
			String usermsg="1";
			r.setMsg(usermsg);
			r.setDetailed(detailed);
			return r;
		}
		
	};
	
	/**
	 * 人脸检测和导入数据
	 * @param state 
	 * @param sfzid 
	 * @throws Throwable 
	 */
	public boolean addWhitePersion(String facepath, String name, String phone,String detailed,String sex, String sfzid, String state,int id,String num,String nameone) throws Throwable {
		boolean ret = false;
		 String imgpath = facepath.toLowerCase();
		 if (imgpath.contains(".png")) {
                imgpath = png2jpg(imgpath);
            }
		 
		 if (imgpath.contains(".jpg")) {
			 List<String> retList = detectFace(imgpath);
			 if(retList != null && retList.size() == 2){
			 int gender=0;
			 if(sex.equals("男")){
				 gender=1;
			 }
			 
			 Shooting sh = new Shooting();
			 sh = pushMapper.selcetShootingname(detailed);
			 String TimeSex=sh.getIpurl();
			 String TimeSex2 = sh.getDbname();
			 String personImportServer =TimeSex+"/api/v1/person/import";
			 long dbid = Long.valueOf(TimeSex2).longValue();
			 ret = addWhitePersionto(personImportServer, name, gender, dbid, retList.get(0), retList.get(1),sfzid,state,id,num,nameone);
		 }else {
             mLogger.error("人脸检测失败 " + imgpath);
         }
     }
 
		return ret;
	}
	
	
	/**
	 * 图片格式转换
	 * @param pngFile
	 * @return
	 */
	public static String png2jpg(String pngFile) {
		String newFile = null;
		if (pngFile != null && pngFile.toLowerCase().contains(".png")) {
			try {
				// read image file
				BufferedImage bufferedImage = ImageIO.read(new File(pngFile));
				newFile = pngFile.replace(".png", ".jpg");
				ImageIO.write(bufferedImage, "jpg", new File(newFile));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return newFile;
	}
	
	public List<String> detectFace(String imgpath) throws Throwable {
	     String feature = null;
	        String face_image = null;
	        List<String> retList = new ArrayList<String>();
	        String json = null;
	        String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
			String TimeSex=readTxT.readTxtLine(txtPath, 1);
	        String detectFaceFileServer=TimeSex+"/api/v1/tool/detectFaceInFile";
	        String wximgpath = getdownimg(imgpath);
	        json = doPostFile(detectFaceFileServer, "file", wximgpath);
	        if (json != null) {
	            //System.out.print(json + "\n");
	            try {
	                JsonParser parser = new JsonParser(); // 创建JSON解析器
	                JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	                int errorcode = object.get("errorCode").getAsInt();
	                if (errorcode == 0) {
	                    JsonObject dataobject = object.get("data").getAsJsonObject();
	                    if (dataobject != null) {
	                        JsonArray array = dataobject.get("result").getAsJsonArray();
	                        if (array.size() > 0) {
	                            JsonObject subObject = array.get(0).getAsJsonObject();

	                            feature = subObject.get("feature").getAsString();
	                            face_image = subObject.get("face_image").getAsString();
	                            retList.add(feature);
	                            retList.add(face_image);
	                        }
	                    }
	                } else {
	                    mLogger.error("detectFace " + json);
	                }
	            } catch (JsonSyntaxException e) {
	                e.printStackTrace();
	            }
	        } else {
	            mLogger.error("connect detectFace error");
	        }
	        return retList;
	}
	
	/**
	 * 通过url下载图片
	 */
	public String getdownimg(String wxpath)throws Exception{
		Date data=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String newData = dateFormat.format(data);
		String filename="/home/apache-tomcat-7.0.47/webapps/wximg/"+newData+"01"+".jpg";
		// 构造URL
	    URL url = new URL(wxpath);
	    // 打开连接
	    URLConnection con = url.openConnection();
	    // 输入流
	    InputStream is = con.getInputStream();
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流
	    OutputStream os = new FileOutputStream(filename);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕，关闭所有链接
	    os.close();
	    is.close();
	    return filename;
	}
	
	public String doPostFile(String urlStr, String paramName,String filePath) {
		 String result = null;
	        @SuppressWarnings("resource")
	        HttpClient httpclient = new DefaultHttpClient();
	        HttpPost post = new HttpPost(urlStr);
	        post.addHeader("Authorization", getHeader(Localfaceuser, passwork));
	        FileBody fileBody = new FileBody(new File(filePath));
	       
	        StringBody stringBody = null;
	        try {
	            stringBody = new StringBody(paramName);
	        } catch (UnsupportedEncodingException e) {
	            mLogger.info("doPostFile UnsupportedEncodingException " + e.toString());
	        }

	        MultipartEntity entity = new MultipartEntity();
	       
	        entity.addPart("file", fileBody);
	        entity.addPart("desc", stringBody);
	        post.setEntity(entity);

	        HttpResponse httpResp;
			try {
				
				httpResp = httpclient.execute(post);
				if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
					result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
				} else {
					mLogger.info("getStatusCode " + httpResp.getStatusLine().getStatusCode());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	        httpclient.getConnectionManager().shutdown();
	        return result;
	}
	
	public boolean addWhitePersionto(String personServer, String name,int gender, long dbId, String features, String face_image,String sfzid, String state,int id,String num,String nameone) {
        boolean ret = false;
        String A = "1";
        String B = "2";
        String C ="0";
        JsonObject object = new JsonObject();
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+1);
     	Date date=curr.getTime();  
     	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");  
     	String validTo = sdf2.format(date);
     	
     	Calendar curr2 = Calendar.getInstance();
        curr2.set(Calendar.DATE,curr2.get(Calendar.DATE)+1);
      	Date date2=curr2.getTime();  
      	SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd");  
      	String validTo2= sdf3.format(date2);
      	String numa = null;
 
        if(num.equals(A)||num.equals(C)){
        	object.addProperty("validTo", validTo);
        	numa = validTo;
        }else if(num.equals(B)) {
        	object.addProperty("validTo", validTo2);
        	numa = validTo2;
		}  
        object.addProperty("name", name);
        object.addProperty("idCard", sfzid);
        object.addProperty("gender", gender);
        object.addProperty("dbId", dbId);
        object.addProperty("features", features);
        object.addProperty("imageData", face_image);
        String jsonstr = object.toString();
        jsonstr = "[" + jsonstr + "]";

        String json = doPostJson(personServer, jsonstr);
        System.out.println(json.toString());
        if (json != null) {
            JsonParser parser = new JsonParser(); // 创建JSON解析器
            object = (JsonObject) parser.parse(json); // 创建JsonObject对象
            int errorcode = object.get("errorCode").getAsInt();
            if (errorcode == 0) {
            	String yindex ="1";
            	try {
					updateUserState(id,yindex,numa,num,nameone);
				} catch (Exception e) {
					e.printStackTrace();
				}
                ret = true;
            }
            mLogger.info(name + "  " +json);
        } else {
            mLogger.error("connect addWhitePersion error");
        }
        return ret;
	}
	
	public String doPostJson(String urlStr, String jsonstr) {
        String result = null;
        HttpPost httpPost = new HttpPost(urlStr);

        try {
            httpPost.addHeader("Authorization", getHeader(Localfaceuser, passwork));
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // httpPost.setHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr, "UTF-8");
            se.setContentType(CONTENT_TYPE_TEXT_JSON);
            httpPost.setEntity(se);
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实
            
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
                mLogger.info("getStatusCode " + httpResp.getStatusLine().getStatusCode());
            }
        } catch (ConnectTimeoutException e) {
            mLogger.info("doPostJson ConnectTimeoutException " + e.toString());
        } catch (UnsupportedEncodingException e) {
            mLogger.info("doPostJson UnsupportedEncodingException " + e.toString());
        } catch (IOException e) {
            mLogger.info("doPostJson IOException " + e.toString());
        } catch (Exception e) {
            mLogger.info("doPostJson Exception " + e.toString());
        }

        return result;
	}
	
 	/**
     * 构造Basic Auth认证头信息
     * 
     * @return
     */
    private  String getHeader(String username, String password) {
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
    }
    
	/**
	 * 更新用户状态
	 */
	public void updateUserState(int id,String yindex,String numa,String num,String nameone){
		int yid = id;
		String yindate=yindex;
		String state=numa;
		Date data=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String yupdatetime = dateFormat.format(data);
        String visitorstype;
        String A ="1";
        String B ="2";
        String C ="0";
        String gun = nameone;
        if(num.equals(A)){
        	visitorstype="1";
        	pushMapper.updateUserState(id,yindate,state,yupdatetime,visitorstype,gun);
        }else if(num.equals(B)) {
        	visitorstype="2";
        	pushMapper.updateUserState(id,yindate,state,yupdatetime,visitorstype,gun);
		}else if(num.equals(C)){
			visitorstype="0";
        	pushMapper.updateUserState(id,yindate,state,yupdatetime,visitorstype,gun);
		}
		
	}
	
	/**
	 * 更新禁止用户状态
	 */
	public void updateUserState2(int id,String state2,String validTo,String num){
		int yid = id;
		String yindate=state2;
		Date data=new Date();
		Date data2=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String yupdatetime = dateFormat.format(data);
        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyyMMdd");
        String state = dateFormat2.format(data2);
        String visitorstype=null;
        String gun = null;
        pushMapper.updateUserStatenull(id,yindate,state,yupdatetime,visitorstype,gun);
	
		
	}
	
	
    /**
     * 删除用户
     * @param id
     * @return
     */
	 public Returnxx Deleuserfin(String id,String phoneidd){
		 	String msg=null;
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        Visitors s =pushMapper.addqueryUserById(phoneidd);
	        String detailed2 = s.getYaddress();
	        String nameone = s.getGun();
	        Shooting sh = new Shooting();
			sh = pushMapper.selcetShootingname(detailed2);
			String TimeSex=sh.getIpurl();
	        String personDeleServer = TimeSex+"/api/v1/person/"+id;
	        String json =DeledoBasicuser(personDeleServer,params);
	        Returnxx rb = new Returnxx();
	        if (json != null) {
	            JsonParser parser = new JsonParser(); // 创建JSON解析器
	            JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	            int errorcode = object.get("errorCode").getAsInt();
	            if (errorcode == 0) {
	            	msg="1";
	            	String state1 = "0";
	            	Visitors u =pushMapper.addqueryUserById(phoneidd);
	            	int id1 = u.getYid();
	            	String detailed =u.getYaddress();	            	
	            	String validTo=null;
	            	String num = null;
	            	updateUserState2(id1,state1,validTo,num);
	            	rb.setMsg(msg);
	            	rb.setDetailed(detailed);
	            	return rb;
	            	}else{
	            	msg="0";
	            	rb.setMsg(msg);
	            	return rb;
	            	}
	            }else {
					msg="0";
	            	rb.setMsg(msg);
	            	return rb;
				}
		 
		 
	 }
	 
	 
	 public String DeledoBasicuser(String urlStr,List<NameValuePair> params) {
	        String result = null;
	        HttpDelete httpDelete = new HttpDelete(urlStr);

	        try {
	        	httpDelete.addHeader("Authorization", getHeader(Localfaceuser, passwork));
	           // HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集-8");
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpDelete);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	                mLogger.info("doBasicAuthPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
	            }
	        } catch (ConnectTimeoutException e) {
	            mLogger.info("doBasicAuthPost ConnectTimeoutException " + e.toString());
	        } catch (UnsupportedEncodingException e) {
	            mLogger.info("doBasicAuthPost UnsupportedEncodingException " + e.toString());
	        } catch (IOException e) {
	            mLogger.info("doBasicAuthPost IOException " + e.toString());
	        } catch (Exception e) {
	            mLogger.info("doBasicAuthPost Exception " + e.toString());
	        }

	        return result;
	    }
	 
	 
	    public long  getUserID(String idCard) {
	    	Visitors u =pushMapper.addqueryUserById(idCard);
			String phone = u.getYphone();
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        String txtPath ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
	        String TimeSex2=readTxT.readTxtLine(txtPath, 2);
			long dbid = Long.valueOf(TimeSex2).longValue();
	        params.add(new BasicNameValuePair("dbIds", ""+dbid));
	        params.add(new BasicNameValuePair("idCard", phone));
	        long userid=0;
	        //接口不支持精确查询
	        String txtPath1 ="/home/apache-tomcat-7.0.47/webapps/configSEX.txt";
			String TimeSex=readTxT.readTxtLine(txtPath1, 1);
	        String personQueryServer = TimeSex+"/api/v1/person/query";
	        String json = DeledoBasicAuthPost(personQueryServer, params);
	        if (json != null) {
	            JsonParser parser = new JsonParser(); // 创建JSON解析器
	            JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	            int errorcode = object.get("errorCode").getAsInt();
	            if (errorcode == 0) {
	                JsonObject dataobject = object.get("data").getAsJsonObject();
	                if (dataobject != null) {
	                    JsonArray array = dataobject.get("content").getAsJsonArray();
	                    for (int i = 0; i < array.size(); i++) {
	                        JsonObject subObject = array.get(i).getAsJsonObject();
	                        String idCard1 = subObject.get("idCard").getAsString();
	                        if (idCard1 != null && idCard1.equals(phone)) {
	                            userid = subObject.get("id").getAsLong();
	                            break;
	                        }
	                    }
	                }
	            }
	        } else {
	           System.out.println("查询出错了");
	        }
	        
	        return userid;
	    }
	    
	    
	    public String DeledoBasicAuthPost(String urlStr, List<NameValuePair> params) {
	        String result = null;
	        HttpPost httpPost = new HttpPost(urlStr);

	        try {
	            httpPost.addHeader("Authorization", getHeader(Localfaceuser, passwork));
	            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
	            httpPost.setEntity(entity);// 设置参数实体
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	                mLogger.info("doBasicAuthPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
	            }
	        } catch (ConnectTimeoutException e) {
	            mLogger.info("doBasicAuthPost ConnectTimeoutException " + e.toString());
	        } catch (UnsupportedEncodingException e) {
	            mLogger.info("doBasicAuthPost UnsupportedEncodingException " + e.toString());
	        } catch (IOException e) {
	            mLogger.info("doBasicAuthPost IOException " + e.toString());
	        } catch (Exception e) {
	            mLogger.info("doBasicAuthPost Exception " + e.toString());
	        }

	        return result;
	    }
	    

		/**
		 * 根据用户姓名和手机
		 */
		public void selectFinPhoneorUserNamefin(String phonename,
				String nameonefin, String yaddressallall,String pageNow, Model model) {
			Page page = null;  
		    List<Visitors> products = new ArrayList<Visitors>();
		    String kz ="";
		    String yphone = phonename;
		    String yname = nameonefin+"%";
		    String yaddress = yaddressallall;
		    List<Shooting> shooting = new ArrayList<Shooting>();
		    if(yphone==null||yphone.equals(kz)){
		    	int totalCount = (int) pushMapper.getProductsCount2(yname,yaddress);
				  
			    if (pageNow != null) {  
			        page = new Page(totalCount, Integer.parseInt(pageNow));  
			        products = this.pushMapper.selectnameonefinPage(page.getStartPos(),yname,yaddress, page.getPageSize());

			    } else {  
			        page = new Page(totalCount, 1);  
			        products = this.pushMapper.selectnameonefinPage(page.getStartPos(),yname,yaddress, page.getPageSize()); 
			   
			    }
			    shooting = pushMapper.selcetShooting(yaddress);
			    model.addAttribute("shooting",shooting);
			    model.addAttribute("products", products);
			    model.addAttribute("phonename", phonename); 
			    model.addAttribute("nameonefin", nameonefin); 
			    model.addAttribute("page", page);
			    model.addAttribute("yaddress", yaddress);
		    }
		    if(yname==null||yname.equals(kz)){
		    	int totalCount = (int) pushMapper.getProductsCount3(yphone,yaddress);
				  
			    if (pageNow != null) {  
			        page = new Page(totalCount, Integer.parseInt(pageNow));
			        products = this.pushMapper.selectFinPhoneorUserNameu(page.getStartPos(),yphone, yaddress,page.getPageSize());

			    } else {  
			        page = new Page(totalCount, 1);  
			        products = this.pushMapper.selectFinPhoneorUserNameu(page.getStartPos(),yphone, yaddress,page.getPageSize()); 
			   
			    }  
			    shooting = pushMapper.selcetShooting(yaddress);
			    model.addAttribute("shooting",shooting);
			    model.addAttribute("products", products);
			    model.addAttribute("phonename", phonename);
			    model.addAttribute("nameonefin", nameonefin); 
			    model.addAttribute("page", page);
			    model.addAttribute("yaddress", yaddress);
		    }
		    if(yphone!=null&&!yphone.equals(kz)&&yname!=null&&!yname.equals(kz)){
		    	int totalCount = (int) pushMapper.getProductsCount4(yphone,yname,yaddress);
				  
			    if (pageNow != null) {  
			        page = new Page(totalCount, Integer.parseInt(pageNow));  
			        products = this.pushMapper.selectallFInPage(page.getStartPos(),yphone,yname,yaddress, page.getPageSize());

			    } else {  
			        page = new Page(totalCount, 1);  
			        products = this.pushMapper.selectallFInPage(page.getStartPos(),yphone,yname, yaddress,page.getPageSize()); 
			   
			    } 
			    shooting = pushMapper.selcetShooting(yaddress);
			    model.addAttribute("shooting",shooting);
			    model.addAttribute("products", products);  
			    model.addAttribute("phonename", phonename); 
			    model.addAttribute("nameonefin", nameonefin); 
			    model.addAttribute("page", page);
			    model.addAttribute("yaddress", yaddress);
		    }
		  
		}
		
		/**
		 * 根据条件查询用户信息
		 */
		public List<Visitors> selectloufin(String yid) {
			List<Visitors> products = new ArrayList<Visitors>();
			products = pushMapper.selecfinuserlou(yid);
			return products;
		}

		public List<Unitdoor> selectloufinuser(String yaddressallall) {
			List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
			String address = yaddressallall;
			unitdoor = pushMapper.selecUnitdoor(address);
			return unitdoor;
		}
		
		/**
		 * 用户单元楼和用户姓名更新
		 */
		public Returnxx UpselcetUserXxFin(int yid, String yunitdoor,
				String yaddress,String yname) {
			Returnxx rb  = new Returnxx();
			try {
				Date data=new Date();
		        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        String updatetime = dateFormat.format(data);

				pushMapper.UpselectFinto(yname, yunitdoor, yid,updatetime);
			} catch (Exception e) {
				String msg="0";
				rb.setMsg(msg);
				return rb;
			}
			String msg ="1";
			String detailed=yaddress;
			rb.setDetailed(detailed);
			rb.setMsg(msg);
			return rb;
		}
		/**
		 * 白名单和黑名单的赛选
		 */
		public void showbaiheiuserxinxi(String pageNow, String name,
				String index, Model model) {
			Page page = null;  
		    List<Visitors> products = new ArrayList<Visitors>();   
		    List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
		    List<Shooting> shooting = new ArrayList<Shooting>();
		    String Celladdress1=name;
		    String yindate =index;
		    int totalCount = (int) pushMapper.getProductsCountbaihei(Celladdress1, yindate);
		  
		    if (pageNow != null) {  
		        page = new Page(totalCount, Integer.parseInt(pageNow));  
		        products = this.pushMapper.selectProductsByPagebaihei(page.getStartPos(),Celladdress1,yindate, page.getPageSize());

		    } else {  
		        page = new Page(totalCount, 1);  
		        products = this.pushMapper.selectProductsByPagebaihei(page.getStartPos(),Celladdress1,yindate, page.getPageSize()); 
		   
		    }
		    String address=name;
		    shooting = pushMapper.selcetShooting(address);
		    model.addAttribute("shooting",shooting);
		    model.addAttribute("products", products);
		    model.addAttribute("address", address);
		    model.addAttribute("page", page);
		    model.addAttribute("yindate", yindate);
			
		}
		
		/**
		 * 更新访客
		 */
	public Returnxx upfkuseronetwo (String id,String num){
		Returnxx rb  = new Returnxx();
		String A = "1";
        String B = "2";
/*		Calendar curr = Calendar.getInstance();
        curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+1);
     	Date date=curr.getTime();  
     	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");  
     	String validTo = sdf2.format(date);*/
     	
     	
      	
      	Date data3=new Date();
        SimpleDateFormat dateFormat3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updatetime = dateFormat3.format(data3);
        
        if(num.equals(A)){
        	Calendar curr = Calendar.getInstance();
            curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+1);
         	Date date=curr.getTime();  
         	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");  
         	String validTo = sdf2.format(date);
        	String yindate="1";
        	String yupdatetime =updatetime;
        	String state =validTo;
        	String yid =id;
        	String visitorstype =num;
        	pushMapper.upfkoneuserend(yindate, yupdatetime, state, yid,visitorstype);
        }else {
        	Calendar curr2 = Calendar.getInstance();
            curr2.set(Calendar.DATE,curr2.get(Calendar.DATE)+1);
          	Date date2=curr2.getTime();  
          	SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd");  
          	String validTo2= sdf3.format(date2);
          	String yindate="1";
        	String yupdatetime =updatetime;
        	String state =validTo2;
        	String yid =id;
        	String visitorstype =num;
          	pushMapper.upfkoneuserend(yindate, yupdatetime, state, yid,visitorstype);
		}
        Visitors v2 = new Visitors();      
        v2 = pushMapper.addqueryUserById(id);
        String yaddress=v2.getYaddress();
        String msg ="1";
		String detailed=yaddress;
		rb.setDetailed(detailed);
		rb.setMsg(msg);
		return rb;
	}
	
		/**
		 * 禁止用户
		 */
		public Returnxx delefkuseronetwo(String id) {
			Returnxx rb = new Returnxx();
			Date data3=new Date();
	        SimpleDateFormat dateFormat3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        String updatetime = dateFormat3.format(data3);
	        
	        Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
	        String stateupdatetime = dateFormat.format(data);
	        
			String yindate="0";
			String yupdatetime=updatetime;
			String state = stateupdatetime;
			String yid = id;
			String visitorstype = null;
			pushMapper.upfkoneuserend(yindate, yupdatetime, state, yid,visitorstype);
			
			Visitors v2 = new Visitors();      
	        v2 = pushMapper.addqueryUserById(id);
	        String yaddress=v2.getYaddress();
	        String msg ="1";
			String detailed=yaddress;
			rb.setDetailed(detailed);
			rb.setMsg(msg);
			return rb;
		}
}
